﻿using InventoryIssue.API.Read.Application.Command.CharHub;
using InventoryIssue.API.Read.Extensions;
using InventoryIssue.Dtos;
using InventoryIssue.ErrorCode;
using InventoryIssue.Infrastructrue.Implement;
using MediatR;
using Microsoft.AspNetCore.SignalR;
using SqlSugar;
using Warehouse.Domian.Model;

namespace InventoryIssue.API.Read.Application.Handler.CharHub
{
    public class GetStorageStockHandler : IRequestHandler<GetStorageStockCommand, APIResult<List<StorageStockDto>>>
    {
        private readonly DatabaseContext database;
        private readonly IHubContext<ChatHub> hubContext;

        public GetStorageStockHandler(DatabaseContext database,IHubContext<ChatHub> hubContext)
        {
            this.database = database;
            this.hubContext = hubContext;
        }
        public async Task<APIResult<List<StorageStockDto>>> Handle(GetStorageStockCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<StorageStockDto>> result = new APIResult<List<StorageStockDto>>();
            var res = database.SqlSugar.Queryable<Stocking>().GroupBy(x=>x.StorageId).
                Select(x => new StorageStockDto { StorageId = x.StorageId, Quantity = SqlFunc.AggregateSum(x.IncomingQuantity) })
                .ToList();
            await hubContext.Clients.All.SendAsync("ReceiveStockData", res);
            result.Message = "显示成功";
            result.Code = APIEnum.Ok;
            result.Data = res;
            return result;
        }
    }
}
